<?php

namespace App\Models;

use App\Exceptions\ApiException;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

/**
 * This is the model class for table "user_notifications"
 *
 * @property string $id
 * @property string $uid 用户ID
 * @property string $type 类型 1充值成功 2充值失败 3提现成功 4提现失败
 * @property string $amount 金额
 * @property string $read 是否已读 1已读 0未读
 * @property string $created_at
 * @property string $updated_at
 */
class UserNotification extends BaseModel
{
    use HasDateTimeFormatter;

    protected $table = 'user_notifications';
    protected $guarded = [];


    protected $template = [
        USER_NOTIFICATION_DEPOSIT_SUCCESS => [
            'title' => "充值成功",
            'body' => "您充值成功:amount",
        ],
        USER_NOTIFICATION_DEPOSIT_FAIL => [
            'title' => "充值失败",
            'body' => "您充值失败:amount",
        ],
        USER_NOTIFICATION_WITHDRAW_SUCCESS => [
            'title' => "提现成功",
            'body' => "您提现成功:amount",
        ],
        USER_NOTIFICATION_WITHDRAW_FAIL => [
            'title' => "提现失败",
            'body' => "您提现失败:amount",
        ]
    ];


    public function history($params)
    {
        $result = self::list(["*"], ['uid' => $params['uid']]);
        foreach ($result['list'] as &$v) {
            $v['title'] = __($this->template[$v['type']]['title'], ['amount' => asMoney($v['amount'])], $params['lang']);
            $v['body'] = __($this->template[$v['type']]['body'], ['amount' => asMoney($v['amount'])], $params['lang']);
        }
        return $result;
    }

    public function detail($params)
    {
        /**
         * @var $result UserNotification
         */
        $result = self::query()->where(['id' => $params['id'], 'uid' => $params['uid']])->first();
        if (!$result) {
            throw new ApiException("数据不存在");
        }

        if ($result->read == 0) {
            $result->update(['read' => 1]);
        }

        $result = $result->toArray();
        $result['title'] = __($this->template[$result['type']]['title'], ['amount' => asMoney($result['amount'])], $params['lang']);
        $result['body'] = __($this->template[$result['type']]['body'], ['amount' => asMoney($result['amount'])], $params['lang']);

        return $result;
    }

}
